// pages/cart/cart.js
import request from '../../utils/request'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked: true,
    allChecked: true,
    cartGoodsList: [],
    totalPrice: 0,
    // 状态栏高度
    statusBarHeight: wx.getStorageSync('statusBarHeight') + 'px',
    statusBarPaddingTop: wx.getStorageSync('statusBarHeight') + 50 + 'px',
    // 导航栏高度
    navigationBarHeight: wx.getStorageSync('navigationBarHeight') + 'px',
    // 胶囊按钮高度
    menuButtonHeight: wx.getStorageSync('menuButtonHeight') + 'px',
    // 导航栏和状态栏高度
    navigationBarAndStatusBarHeight:
      wx.getStorageSync('statusBarHeight') +
      wx.getStorageSync('navigationBarHeight') +
      'px'
  },
  async onChange(event) {
    this.setData({
      checked: event.detail,
    });
    let gid = event.currentTarget.dataset.gid;
    let isSelect = event.detail ? 1 : 0
    console.log(gid, isSelect)
    let userInfo = wx.getStorageSync('youxuan-user-userInfo')
    let result = await request("/cartdetail/changeSelect?gid=" + gid + "&uid=" + userInfo.id + "&isSelect=" + isSelect, {}, "POST")
    console.log(result)
    this.getCartGoodsList()

  },
  async onAllChange(event) {
    this.setData({
      allChecked: event.detail,
    });
    console.log(event.detail)
    var goodsList = this.data.cartGoodsList.map(function (item) {
      item.isSelect = event.detail ? "1" : "0"
      return item
    })
    for (var i = 0; i < goodsList.length; i++) {
      var goods = goodsList[i];
      let userInfo = wx.getStorageSync('youxuan-user-userInfo')
      let result = await request("/cartdetail/changeSelect?gid=" + goods.id + "&uid=" + userInfo.id + "&isSelect=" + goods.isSelect, {}, "POST")
      console.log(result)
    }
    this.getCartGoodsList()
  },
  async onNumChange(e) {
    let num = e.detail
    let gid = e.currentTarget.dataset.gid
    let userInfo = wx.getStorageSync('youxuan-user-userInfo')
    let result = await request(`/cartdetail/changeNum?gid=${gid}&uid=${userInfo.id}&num=${num}`, {}, "POST")
    console.log(result)
    this.getCartGoodsList()
  },
  async overlimit(e){
    Dialog.confirm({
      title: '删除提示',
      message: '确定要删除该商品吗？',
    }).then(async () => {
      let gid = e.currentTarget.dataset.gid
      let userInfo = wx.getStorageSync('youxuan-user-userInfo')
      let result = await request("/cartdetail/delete?gid="+gid+"&uid="+userInfo.id,{},"POST")
      if (result.code == 200) {
        wx.showToast({
          title: '删除成功',
          icon:"none",
        })
        this.getCartGoodsList()
      }
    }).catch(() => {
      // on cancel
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {


    let token = wx.getStorageSync('youxuan-user-token');
    if (!token) {
      wx.showModal({
        title: '登录提示',
        content: '您还未登录，请先登录',
        confirmText: '去登陆',
        confirmColor: '#f0cf4a',
        cancelColor: '#999',
        success(res) {
          if (res.confirm) {
            wx.reLaunch({
              url: '/pages/login/login',
            })
            return
          } else if (res.cancel) {
            wx.reLaunch({
              url: '/pages/index/index',
            })
            return
          }
        }
      })
    }

    this.getCartGoodsList()


    const { statusBarHeight, platform } = wx.getSystemInfoSync()
    const { top, height } = wx.getMenuButtonBoundingClientRect()

    // 状态栏高度
    wx.setStorageSync('statusBarHeight', statusBarHeight)
    // 胶囊按钮高度 一般是32 如果获取不到就使用32
    wx.setStorageSync('menuButtonHeight', height ? height : 32)

    // 判断胶囊按钮信息是否成功获取
    if (top && top !== 0 && height && height !== 0) {
      const navigationBarHeight = (top - statusBarHeight) * 2 + height
      // 导航栏高度
      wx.setStorageSync('navigationBarHeight', navigationBarHeight)
    } else {
      wx.setStorageSync(
        'navigationBarHeight',
        platform === 'android' ? 48 : 40
      )
    }
  },
  async getCartGoodsList() {
    var userInfo = wx.getStorageSync('youxuan-user-userInfo')
    if (userInfo) {
      let cartGoodsList = await request('/cart/goods/list/' + userInfo.id)
      this.setData({
        cartGoodsList: cartGoodsList.data
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  toPayment(e) {
    console.log(e)
    if (e.currentTarget.dataset.gids == "") {
      wx.showToast({
        title: '请选择商品',
        icon:"none"
      })
    }else{
      wx.navigateTo({
        url: '/pages/confirmOrder/confirmOrder?gids=' + e.currentTarget.dataset.gids,
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCartGoodsList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function (e) {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})